<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 5.2</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="5.1.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="5.3.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P1">Part I. The Language</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#5">Chapter 5. Functions</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><a name="Vararg"><h2>5.2 &ndash; Variable Number of Arguments</h2></a>

<p>Some functions in Lua receive a variable number of arguments.
For instance, we have already called <code>print</code>
with one, two, and more arguments.

<p>Suppose now that we want to redefine <code>print</code> in Lua:
Perhaps our system does not have a <code>stdout</code> and so,
instead of printing its arguments,
<code>print</code> stores them in a global variable,
for later use.
We can write this new function in Lua as follows:
<pre>
    printResult = ""
    
    function print (...)
      for i,v in ipairs(arg) do
        printResult = printResult .. tostring(v) .. "\t"
      end
      printResult = printResult .. "\n"
    end
</pre>
The three dots (<code>...</code>) in the parameter list indicate that
the function has a variable number of arguments.
When this function is called,
all its arguments are collected in a single table,
which the function accesses as a hidden parameter
named <code>arg</code>.
Besides those arguments,
the <code>arg</code> table has an extra field, <code>n</code>,
with the actual number of arguments collected.

<p>Sometimes, a function has some fixed parameters
plus a variable number of parameters.
Let us see an example.
When we write a function that returns multiple values
into an expression,
only its first result is used.
However, sometimes we want another result.
A typical solution is to use dummy variables;
for instance, if we want only the second result from <code>string.find</code>,
we may write the following code:
<pre>
    local _, x = string.find(s, p)
    -- now use `x'
    ...
</pre>
An alternative solution is to define a <code>select</code> function,
which selects a specific return from a function:
<pre>
    print(string.find("hello hello", " hel"))         --> 6  9
    print(select(1, string.find("hello hello", " hel"))) --> 6
    print(select(2, string.find("hello hello", " hel"))) --> 9
</pre>
Notice that a call to <code>select</code> has always one fixed argument,
the <em>selector</em>,
plus a variable number of extra arguments
(the returns of a function).
To accommodate this fixed argument,
a function may have regular parameters before the dots.
Then, Lua assigns the first arguments to those parameters
and only the extra arguments (if any) go to <code>arg</code>.
To better illustrate this point, assume a definition like
<pre>
    function g (a, b, ...) end
</pre>
Then, we have the following mapping from arguments to parameters:
<pre>
    CALL            PARAMETERS
       
    g(3)             a=3, b=nil, arg={n=0}
    g(3, 4)          a=3, b=4, arg={n=0}
    g(3, 4, 5, 8)    a=3, b=4, arg={5, 8; n=2}
</pre>

<p>Using those regular parameters,
the definition of <code>select</code> is straightforward:
<pre>
    function select (n, ...)
      return arg[n]
    end
</pre>

<p>Sometimes, a function with a variable number of arguments needs to
pass them all to another function.
All it has to do is to call the other function using
<code>unpack(arg)</code> as argument:
<code>unpack</code> will return all values in <code>arg</code>,
which will be passed to the other function.
A good example of this use is a function to
write formatted text.
Lua provides separate functions to format text
(<code>string.format</code>,
similar to the <code>sprintf</code> function from the C library)
and to write text (<code>io.write</code>).
Of course, it is easy to combine both functions into a single one,
except that this new function has to pass a variable number of
values to <code>format</code>.
This is a job for <code>unpack</code>:
<pre>
    function fwrite (fmt, ...)
      return io.write(string.format(fmt, unpack(arg)))
    end
</pre>

<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="5.3.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

